package com.example.controller;

import com.example.config.ServiceMQTT;
import com.example.mapper.PointEqipmentMapper;
import com.example.mapper.infoMapper;
import com.example.mapper.omMapper;
import com.example.pojo.dev.fmDevTree;
import com.example.pojo.dev.icDevPoint;
import com.example.resule.Result;
import com.example.service.FileService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * @BelongsProject: drools
 * @BelongsPackage: com.example.controller
 * @Author: dyz
 * @CreateTime: 15:51
 * @Version: 1.0
 */

@RestController
@RequestMapping("/Maintaindrools")
public class MaintainController {

    @Autowired
    private infoMapper infoMapper;
    @Autowired
    private PointEqipmentMapper pointEqipmentMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private omMapper omMapper;


    @Autowired
    MaintainDrools runtimeDrools;
    @Autowired
    private ServiceMQTT serviceMQTT;


//
//    @ApiOperation(value = "添加规则", notes = "测试用接口", httpMethod = "POST")
//    @PostMapping(value = "/insertdrools")
//    public Result insertdrools(@RequestBody RuleExcelUser ruleExcelUser) throws IOException, ParseException {
//
//        if (ruleExcelUser.getWhethermatches().equals("类型")){
//            ruleExcelUser.setPointName(ruleExcelUser.getPointName().split(" ")[0]);
//        }
//        List<SeRuleFile> selectbydroolsname = fileMapper.selectRuntimebyfilename(ruleExcelUser.getPointName());
//        if (selectbydroolsname.size() == 0) {
//            ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
//
//            //获取标准 监控对象 拼接为文件名
//            //String filename = upload + ruleExcelUser.getPointName() + "&&" + ruleExcelUser.getStandard() + ".xls";
//            //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
//            //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
//            SeRuleFile seRuleFile = new SeRuleFile();
//            seRuleFile.setFilename(ruleExcelUser.getPointName() );
//            seRuleFile.setUrl("/" + ruleExcelUser.getPointName()+ ".xls");
//            seRuleFile.setWhetherUse(1);
//            seRuleFile.setStandard(ruleExcelUser.getStandard());
//            seRuleFile.setDroolsname(ruleExcelUser.getDroolsname());
//            seRuleFile.setMonitorType(ruleExcelUser.getMonitorType());
//            seRuleFile.setModelId(ruleExcelUser.getModelId());
//            seRuleFile.setAlarmType(ruleExcelUser.getAlarmType());
//
//            String filename = upload  + ruleExcelUser.getPointName()  + ".xls";
//            obj.writeExcel(filename, ruleExcelUser.whethermatches,ruleExcelUser.getStandard(), ruleExcelUser.getPointName(), ruleExcelUser.getRuleExcelUserList(),
//                    ruleExcelUser.getPointName(), " ");
//
//            seRuleFile.setSeason(" ");
//                //存储路径
//            int insertdrools = fileMapper.insertRuntimedrools(seRuleFile);
//
//
//
//            //obj.writeExcel(filename, ruleExcelUser.whethermatches, ruleExcelUser.getPointName(), ruleExcelUser.getRuleExcelUserList(), ruleExcelUser.getPointName());
//
//
//            runtimeDrools.updatekieHepler();
//            return Result.ok();
//        } else {
//            return Result.error().message("已有此监控对象");
//        }
//
//
//    }
//
//    @ApiOperation(value = "删除规则", notes = "测试用接口", httpMethod = "POST")
//    @PostMapping(value = "/delectdrools")
//    public Result delectdrools(@RequestParam("filename") String filename, @RequestParam("standard") String standard) throws ParseException {
//        List<SeRuleFile> selectbydroolsname = fileMapper.selectRuntimebyfilename(filename );
//        for (SeRuleFile seRuleFile : selectbydroolsname) {
//            File file = new File(upload + "/" + seRuleFile.getUrl());
//            //File file = new File("D:/drools.xls");
//            boolean exists = file.exists();
//            int delectbyid = fileMapper.delectRuntimebyfilename(filename );
//            runtimeDrools.updatekieHepler();
//            if (exists) {
//                boolean delete = file.delete();
//                System.out.println(delete);
//            } else {
//                return Result.error().message("文件不存在");
//            }
//
//        }
//        return Result.ok().message("删除成功");
//    }
//
//    @ApiOperation(value = "是否使用规则", notes = "测试用接口", httpMethod = "POST")
//    @PostMapping(value = "/wheathershow")
//    public Result wheathershow(@RequestParam("filename") String filename, @RequestParam("standard") String standard, @RequestParam("whetherUse") int whetherUse) throws ParseException {
//        int i = fileMapper.updateRuntimewhetherUse(filename , whetherUse);
//        runtimeDrools.updatekieHepler();
//        // this.dataxbyuser();
//        if (i > 0) {
//            return Result.ok().message("设置成功");
//        } else {
//            return Result.error();
//        }
//
//
//    }
//    @ApiOperation(value = "修改规则", notes = "测试用接口", httpMethod = "POST")
//    @PostMapping(value = "/updatedrools")
//    public Result updatedrools(@RequestBody RuleExcelUser ruleExcelUser) throws IOException, ParseException {
//
//        if (ruleExcelUser.getWhethermatches().equals("类型")){
//            ruleExcelUser.setPointName(ruleExcelUser.getPointName().split(" ")[0]);
//        }
//
//        List<SeRuleFile> selectbyid = fileMapper.selectrRuntimebyid(ruleExcelUser.getId());
//        for (SeRuleFile seRuleFile : selectbyid) {
//            File file = new File(upload + "/"  + seRuleFile.getUrl());
//            //File file = new File("D:/drools.xls");
//            boolean exists = file.exists();
//            int delectbydroolsname = fileMapper.delectRuntimebyfilename(seRuleFile.getFilename());
//            runtimeDrools.updatekieHepler();
//            if (exists) {
//                boolean delete = file.delete();
//                System.out.println(delete);
//            } else {
//                return Result.error().message("文件不存在");
//            }
//        }
//        ReadExcelRuleEngine obj = new ReadExcelRuleEngine();
////        List<RuleExcelUser> summer = new ArrayList<>();
////        List<RuleExcelUser> winter = new ArrayList<>();
////        for (RuleExcelUser r : ruleExcelUser.getRuleExcelUserList()) {
////            if (r.getSeason().equals("夏季")) {
////                summer.add(r);
////            } else if (r.getSeason().equals("冬季")) {
////                winter.add(r);
////            } else if (r.getSeason().equals("四季")) {
////                summer.add(r);
////                winter.add(r);
////            } else {//防止用户瞎几把写,预留,后期可以根据操作时间,全部写成当季
////
////            }
////        }
//        SeRuleFile seRuleFile = new SeRuleFile();
//        seRuleFile.setFilename(ruleExcelUser.getPointName() );
//        seRuleFile.setUrl("/" + ruleExcelUser.getPointName()+ ".xls");
//        seRuleFile.setWhetherUse(1);
//        seRuleFile.setStandard(ruleExcelUser.getStandard());
//        seRuleFile.setDroolsname(ruleExcelUser.getDroolsname());
//        seRuleFile.setMonitorType(ruleExcelUser.getMonitorType());
//        seRuleFile.setAlarmType(ruleExcelUser.getAlarmType());
//        // seRuleFile.setModelId(ruleExcelUser.getModelId());
//        //将数据添加到execl  文件绝对路径    是否包含    规则名   变量    监控对象
//        String filename = upload  + ruleExcelUser.getPointName()  + ".xls";
//        obj.writeExcel(filename, ruleExcelUser.whethermatches,ruleExcelUser.getStandard(), ruleExcelUser.getPointName(),
//                ruleExcelUser.getRuleExcelUserList(), ruleExcelUser.getPointName(), " ");
//
//        seRuleFile.setSeason(" ");
//        //存储路径
//        int insertdrools = fileMapper.insertRuntimedrools(seRuleFile);
//
//
//        runtimeDrools.updatekieHepler();
//
//        return Result.ok();
//    }

    @ApiOperation(value = "查询设备", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/getomdev")
    public Result getomdev(@RequestParam("keyword") String keyword) throws ParseException {
        List<icDevPoint> pointEquipments = pointEqipmentMapper.disName(keyword);
        List<fmDevTree> selectroot = infoMapper.selectroot();
        //一级
        for (fmDevTree modelTree : selectroot) {
            modelTree.setLevel(1);
            List<fmDevTree> modelTrees = infoMapper.selectbyPid(modelTree.getId());

            //二级
            for (fmDevTree tree : modelTrees) {
                tree.setLevel(2);
                ArrayList<fmDevTree> treeArrayList = new ArrayList<>();
                //三级
                for (icDevPoint pointEquipment : pointEquipments) {
                    if (StringUtils.isNotBlank( pointEquipment.getSubsystemName()) && pointEquipment.getSubsystemName().equals(tree.getSName()) && pointEquipment.getModelId().equals(tree.getModelId())){
                        fmDevTree modelTree1 = new fmDevTree();
                        modelTree1.setDbId(pointEquipment.getDbid());
                        modelTree1.setLevel(3);
                        modelTree1.setSName(pointEquipment.getDevName()+" "+pointEquipment.getDevNumber());
                        modelTree1.setModelId(pointEquipment.getModelId());
                        treeArrayList.add(modelTree1);
                    }
                }
                tree.setChildren(treeArrayList);

            }
            modelTree.setChildren(modelTrees);
        }

        //去除没有三级的 一二级
        for (fmDevTree modelTree : selectroot) {
            Iterator<fmDevTree> iterator1 = modelTree.getChildren().iterator();
            while (iterator1.hasNext()){
                List<fmDevTree> children = iterator1.next().getChildren();
                if (children.size()==0){
                    iterator1.remove();
                }

            }
        }
        Iterator<fmDevTree> iterator = selectroot.iterator();
        while (iterator.hasNext()) {
            List<fmDevTree> children = iterator.next().getChildren();
            if (children.size() == 0) {
                iterator.remove();
            }
        }
//        List<String> strings =new ArrayList<>();
//
//        for (icDevPoint pointEquipment : pointEquipments) {
//            strings.add(pointEquipment.getDeviceName()+" "+pointEquipment.getDevNumber());
//        }

        // this.dataxbyuser();
        return Result.success(selectroot);


    }

    @ApiOperation(value = "处理", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/updatehandle")
    public Result updatehandle(@RequestParam("dbId") int dbId, @RequestParam("maintainType") String maintainType) throws ParseException {
        int i = omMapper.updatehandle(dbId, maintainType, true);
        // this.dataxbyuser();
        if (i > 0) {
            return Result.ok().message("处理完成");
        } else {
            return Result.error();
        }


    }

    @ApiOperation(value = "变量", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/getvarname")
    public Result selectvarname() {
        //查询绑定表
        HashMap<Object, Object> map = new HashMap<>();
        map.put("运行时长", "小时");
        map.put("寿命到期", "天");
        return Result.success(map);
    }

    @ApiOperation(value = "获取部位", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/getposition")
    public Result selectposition(@RequestParam("devName") String devName) {
        String[] split = devName.split(" ");
        List<String> varName = new ArrayList<>();
        List<String> pointName = pointEqipmentMapper.dispointNamebyNumber(split[0],split[1]);
        for (String string : pointName) {
            List<String> strings = omMapper.disvarName(string);
            varName.addAll(strings);

        }
//
        return Result.success(varName);
    }

    @ApiOperation(value = "获取部位", notes = "测试用接口", httpMethod = "POST")
    @PostMapping(value = "/sendout")
    public Result sendout(@RequestParam("devName") String devName) throws MqttException {
//        List<String> strings = omMapper.disposition(devName);
        HashMap<String, String> map = new HashMap<>();
        map.put("sendtype", devName);
        map.put("type", "dev");
        map.put("subsystemBelong", "PFSY-11");
        map.put("systemBelong", "排风系统");
        map.put("sname", "排风机");
        map.put("storey", "排风机");
        map.put("number", "fmDevInfo.getDevNumber()");
        map.put("level", "fmDevInfo.getDevLevel()");
        map.put("messagelevel", "droolsTest.getMessagelevel()");
        map.put("information", "droolsTest.getInformation()");
     //   serviceMQTT.alarm(map);
        return Result.success(devName);
    }


}
